package com.example.app2;

import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.widget.EditText;

import androidx.annotation.Nullable;
import androidx.appcompat.app.AppCompatActivity;

import com.example.app2.Dao.BookDao;
import com.example.app2.pojo.BookInfo;

import java.util.List;

public class RoomActivity extends AppCompatActivity implements View.OnClickListener {

    private EditText viewById;
    private EditText et_name;
    private EditText et_author;
    private EditText et_press;
    private EditText et_price;
    private BookDao bookDao;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_room_write);
        et_name = findViewById(R.id.et_name);
        et_author = findViewById(R.id.et_author);
        et_press = findViewById(R.id.et_press);
        et_price = findViewById(R.id.et_price);
        findViewById(R.id.btn_save).setOnClickListener(this);
        findViewById(R.id.btn_delete).setOnClickListener(this);
        findViewById(R.id.btn_query).setOnClickListener(this);
        findViewById(R.id.btn_update).setOnClickListener(this);
        bookDao = MyApplication.getInstance().getBookDatabase().bookDao();
    }

    @Override
    public void onClick(View v) {
        String name = et_name.getText().toString();
        String author = et_author.getText().toString();
        String press = et_press.getText().toString();
        String price = et_price.getText().toString();
        switch (v.getId())
        {
            case R.id.btn_save: {
                BookInfo info = new BookInfo();
                info.setName(name);
                info.setAuthor(author);
                info.setPress(press);
                info.setPrice(Double.parseDouble(price));
                bookDao.insert(info);
                break;
            }
            case R.id.btn_delete: {
                //根据名字删除
                BookInfo info=bookDao.queryByName(name);
                bookDao.delete(info.getName());
                break;
            }
            case R.id.btn_update:
                //先查出要更新的id，然后再更新对应的，这样就可以连名字也删除
                BookInfo info = bookDao.queryByName(name);
                BookInfo book=new BookInfo();
                book.setId(info.getId());
                book.setName(name);
                book.setAuthor(author);
                book.setPress(press);
                book.setPrice(Double.parseDouble(price));
                bookDao.update(book);
                break;
            case R.id.btn_query:
                List<BookInfo> bookInfos = bookDao.queryAll();
                for (BookInfo bookInfo : bookInfos) {
                    Log.d("tang", bookInfo.toString());
                }

                break;
        }
    }
}
